package show.me.the.money.service.dao;

import java.util.HashMap;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import show.me.the.money.config.schema.Schema;
import show.me.the.money.config.schema.SchemaController;
import show.me.the.money.dao.SimpleDAO;
import show.me.the.money.dao.exception.DataAccessException;
import show.me.the.money.service.core.Service;
import show.me.the.money.util.context.Context;


public abstract class DAOSupportService extends DBSupportService {
	
	private static final Log logger = LogFactory.getLog(DAOSupportService.class);
	
	public void execute(HashMap<String, Object> req,HashMap<String, Object> res, Context ctx) {
		SimpleDAO dao = null;
		int code = 200;
		String msg = "Success";
		
		String schemaId = (String)req.get("schema");
		if(StringUtils.isEmpty(schemaId)){
			code = 401;
			msg = "SchemaIdMissed";
			res.put(Service.RES_CODE,code);
			res.put(Service.RES_MESSAGE, msg);
			return;
		}
		
		Schema sc = SchemaController.instance().getSchema(schemaId);
		
		try{
			dao = new SimpleDAO(sc,ctx);
			if(transactionSupport){
				dao.beginTransaction();
			}
			invoke(req,res,ctx,dao);
			if(transactionSupport){
				dao.commitTransaction();
			}
		}
		catch(DataAccessException e){
			code = 501;
			msg = "DataAccessException:" + e.getMessage();
			res.put(Service.RES_CODE,code);
			res.put(Service.RES_MESSAGE,msg);
			if(transactionSupport){
				try {
					dao.rollbackTransaction();
				} 
				catch (DataAccessException e1) {
					logger.error("dao rollbackTransaction falied:"+ e1.getMessage());
				}
			}
		}
		catch(Exception e){
			code = 599;
			msg = "UnkonwException:" + e.getMessage();
			res.put(Service.RES_CODE,code);
			res.put(Service.RES_MESSAGE,msg);
			if(transactionSupport){
				try {
					dao.rollbackTransaction();
				} 
				catch (DataAccessException e1) {
					logger.error("dao rollbackTransaction falied:"+ e1.getMessage());
				}
			}
		}
		finally{
//			if(dao != null){
//				try {
//					dao.destroy();
//				} 
//				catch (DataAccessException e) {
//					logger.error("DaoDestroyFailed:" + e.getMessage());
//				}
//			}
		}
	}
	
	@Override
	public void dbSupportExecute(HashMap<String, Object> req,
			HashMap<String, Object> res, Context ctx)
			throws DataAccessException {	}
	
	public abstract void invoke(HashMap<String, Object> req,HashMap<String, Object> res, Context ctx,SimpleDAO dao) throws DataAccessException;
	


}
